#include "GridTableWidget.h"
#include <QPainter>
#include <QDebug>
#include <QFont>
#include <QFontMetrics>
#include <QVBoxLayout>

GridTableWidget::GridTableWidget(const QString &title, QWidget *parent)
    : CommonContainer(title, true, 4, parent)
    , m_isEditMode(false)
    , m_gridColumns(4)
    , m_gridRows(4)
{
    setupUI();
    setupConnections();
}

GridTableWidget::~GridTableWidget()
{
}

void GridTableWidget::setupUI()
{
    m_gridWidget = new QWidget(this);
    m_gridWidget->setObjectName("gridTableGridWidget");
    m_gridWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    m_gridLayout = new QGridLayout(m_gridWidget);
    m_gridLayout->setContentsMargins(1,1,1,1);
    m_gridLayout->setHorizontalSpacing(1);
    m_gridLayout->setVerticalSpacing(1);
    
    setContentWidget(m_gridWidget);
}

void GridTableWidget::setupConnections()
{
    connect(this, &CommonContainer::editButtonClicked, this, &GridTableWidget::onEditButtonClicked);
    connect(this, &CommonContainer::editModeChanged, this, &GridTableWidget::onEditModeChanged);
}


void GridTableWidget::addGridTableItem(const GridTableItem &item)
{
    addGridTableItem(item.name, item.value);
}

void GridTableWidget::addGridTableItem(const QString &name, const QString &value)
{
    GridTableItem item;
    item.name = name;
    item.value = value;
    m_gridTableItems.append(item);

    QWidget *itemWidget = new QWidget(m_gridWidget);

    QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);
    itemLayout->setContentsMargins(0, 0, 0, 0);
    itemLayout->setSpacing(0);

    QLineEdit *nameEdit = new QLineEdit(name, itemWidget);
    nameEdit->setObjectName("gridTableEdit");
    nameEdit->setAlignment(Qt::AlignCenter);
    nameEdit->setPlaceholderText("名称");
    nameEdit->setReadOnly(!m_isEditMode);
    nameEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    connect(nameEdit, &QLineEdit::textChanged, this, &GridTableWidget::onValueChanged);
    m_nameEdits.append(nameEdit);
    itemLayout->addWidget(nameEdit);

    QLineEdit *valueEdit = new QLineEdit(value, itemWidget);
    valueEdit->setObjectName("gridTableEdit");
    valueEdit->setAlignment(Qt::AlignCenter);
    valueEdit->setPlaceholderText("数值");
    valueEdit->setReadOnly(!m_isEditMode);
    valueEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    connect(valueEdit, &QLineEdit::textChanged, this, &GridTableWidget::onValueChanged);
    m_valueEdits.append(valueEdit);
    itemLayout->addWidget(valueEdit);

    int index = m_gridTableItems.size() - 1;
    int row = index / m_gridColumns;
    int col = index % m_gridColumns;

    m_gridLayout->addWidget(itemWidget, row, col);

    updateLayout();
}

void GridTableWidget::removeGridTableItem(int index)
{
    if (index < 0 || index >= m_gridTableItems.size()) return;
    
    if (index < m_nameEdits.size() && m_nameEdits[index]) {
        m_nameEdits[index]->deleteLater();
        m_nameEdits.removeAt(index);
    }
    if (index < m_valueEdits.size() && m_valueEdits[index]) {
        m_valueEdits[index]->deleteLater();
        m_valueEdits.removeAt(index);
    }
    
    m_gridTableItems.removeAt(index);
    
    updateLayout();
}

void GridTableWidget::clearGridTableItems()
{
    for (QLineEdit *edit : m_nameEdits) {
        if (edit) edit->deleteLater();
    }
    for (QLineEdit *edit : m_valueEdits) {
        if (edit) edit->deleteLater();
    }
    
    m_nameEdits.clear();
    m_valueEdits.clear();
    m_gridTableItems.clear();
    
    updateLayout();
}

GridTableWidget::GridTableItem GridTableWidget::getGridTableItem(int index) const
{
    if (index >= 0 && index < m_gridTableItems.size()) {
        return m_gridTableItems[index];
    }
    return GridTableItem();
}

QVector<GridTableWidget::GridTableItem> GridTableWidget::getAllGridTableItems() const
{
    return m_gridTableItems;
}

void GridTableWidget::setGridTableValue(int index, const QString &value)
{
    if (index >= 0 && index < m_gridTableItems.size()) {
        m_gridTableItems[index].value = value;
        if (index < m_valueEdits.size() && m_valueEdits[index]) {
            m_valueEdits[index]->setText(value);
        }
    }
}

QString GridTableWidget::getGridTableValue(int index) const
{
    if (index >= 0 && index < m_gridTableItems.size()) {
        return m_gridTableItems[index].value;
    }
    return QString();
}

void GridTableWidget::setGridTableName(int index, const QString &name)
{
    if (index >= 0 && index < m_gridTableItems.size()) {
        m_gridTableItems[index].name = name;
        if (index < m_nameEdits.size() && m_nameEdits[index]) {
            m_nameEdits[index]->setText(name);
        }
    }
}

QString GridTableWidget::getGridTableName(int index) const
{
    if (index >= 0 && index < m_gridTableItems.size()) {
        return m_gridTableItems[index].name;
    }
    return QString();
}

void GridTableWidget::setEditMode(bool enabled)
{
    if (m_isEditMode == enabled) return;
    
    m_isEditMode = enabled;
    
    for (QLineEdit *edit : m_nameEdits) {
        if (edit) {
            edit->setReadOnly(!enabled);
        }
    }
    for (QLineEdit *edit : m_valueEdits) {
        if (edit) {
            edit->setReadOnly(!enabled);
        }
    }
    
    CommonContainer::setEditMode(enabled);
    
    emit editModeChanged(enabled);
}

bool GridTableWidget::isEditMode() const
{
    return m_isEditMode;
}

void GridTableWidget::paintEvent(QPaintEvent *event)
{
    CommonContainer::paintEvent(event);
    QPainter painter(this);
    drawGridBorders(painter);
}

void GridTableWidget::updateLayout()
{
    int itemCount = m_gridTableItems.size();
    m_gridRows = (itemCount + m_gridColumns - 1) / m_gridColumns;
    
    if (m_gridWidget) {
        m_gridWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    }
    
    if (m_gridLayout) {
        for (int i = 0; i < m_gridColumns; ++i) {
            m_gridLayout->setColumnStretch(i, 1);
        }
        for (int i = 0; i < m_gridRows; ++i) {
            m_gridLayout->setRowStretch(i, 1);
        }
    }
    
    update();
}

void GridTableWidget::drawGridBorders(QPainter &painter)
{
    if (!m_gridWidget) return;
    
    QRect gridRect = m_gridWidget->geometry();
    if (gridRect.isEmpty()) return;
    
    QPen pen(QColor("#2881FF"));
    pen.setWidth(1);
    painter.setPen(pen);
    int x = gridRect.left() + 1;
    for (int col = 1; col < m_gridColumns; ++col) {
        x += m_gridLayout->itemAtPosition(0, col - 1)->widget()->width() + (col>1 ? 1 : 0);
        painter.drawLine(x, gridRect.top(), x, gridRect.bottom());
    }
    
    pen.setColor(QColor("#2C4E7E"));
    painter.setPen(pen);
    int y = gridRect.top() + 1;
    for (int row = 1; row < m_gridRows; ++row) {
        y += m_gridLayout->itemAtPosition(row - 1, 0)->widget()->height() + (row>1 ? 1 : 0);
        painter.drawLine(gridRect.left(), y, gridRect.right(), y);
    }
}

void GridTableWidget::onValueChanged()
{
    QLineEdit *sender = qobject_cast<QLineEdit*>(QObject::sender());
    if (!sender) return;
    
    int index = m_nameEdits.indexOf(sender);
    if (index >= 0) {
        m_gridTableItems[index].name = sender->text();
        emit gridTableNameChanged(index, sender->text());
        return;
    }

    index = m_valueEdits.indexOf(sender);
    if (index >= 0) {
        m_gridTableItems[index].value = sender->text();
        emit gridTableValueChanged(index, sender->text());
    }
}

void GridTableWidget::onEditButtonClicked()
{
}

void GridTableWidget::onEditModeChanged(bool enabled)
{
    m_isEditMode = enabled;
    
    for (QLineEdit *edit : m_nameEdits) {
        if (edit) {
            edit->setReadOnly(!enabled);
        }
    }
    for (QLineEdit *edit : m_valueEdits) {
        if (edit) {
            edit->setReadOnly(!enabled);
        }
    }
    
    emit editModeChanged(enabled);
}

